import localforage from "localforage";
export class Local {
    private driver = localforage;
    private namespace = "default";

    constructor(namespace?: string) {
        if (namespace) {
            this.namespace = namespace;
        }
    }

    /**
     * Get item from local storage
     * @param key
     * @returns
     */
    public getItem(key: string): any {
        return this.driver.getItem(`${this.namespace}-${key}`);
    }

    public setItem(key: string, value: any) {
        this.driver.setItem(`${this.namespace}-${key}`, value);
    }

    clear() {
        this.driver.clear();
    }

    public removeItem(key: string) {
        this.driver.removeItem(`${this.namespace}-${key}`);
    }

    public keys() {
        return this.driver.keys().then((keys: string[]) => {
            return Promise.resolve(
                keys.map((key: string) => key.replace(`${this.namespace}-`, ""))
            );
        });
    }

    iterate(callback: (key: string, value: any) => void) {
        this.driver.iterate((value, key) => {
            callback(key.replace(`${this.namespace}-`, ""), value);
        });
    }
}
